package com.glacier.demo.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.glacier.demo.domain.User;
import com.glacier.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * date 2024-01-29 20:43
 *
 * @author glacier
 * @version 1.0
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @SentinelResource(value = "userService-findById", blockHandler = "blockHandlerForGetUser")
    @Override
    public User findById(long id) {
        if (id == 0) {
            throw new RuntimeException("getUserById command failed");
        }
        return new User(id, "admin", "admin1", 25);
    }

    /**
     * blockHandler 函数，原方法调用被限流/降级/系统保护的时候调用
     *
     * @param id
     * @param ex
     * @return
     */
    public User blockHandlerForGetUser(long id, BlockException ex) {
        log.info("流控了 id={}", id, ex);
        return new User(id, "admin1", "123456", 20);
    }
}
